const app = getApp();
const MAX_COUNT_IMAGE = 9;
Page({
  data: {
    authLocationTips: false,
    pageType: 1, // 1添加 2编辑
    equipment_name: "",
    equipmentTypes: [], //设备类型
    equipmentTypeIndex: "",
    equipment_number: "", //设备编号
    villages: [],
    villageIndex: "",
    address: "",
    latitude: "",
    longitude: "",
    all_url_arrs: [],
    url_arrs: [],
    max_count_img: MAX_COUNT_IMAGE,
    replace_number: "",
    franchiseers: [], //加盟商列表
    franchiseerIndex: "",
  },




  onLoad: function (options) {
    const pageType = options.type || 1;
    let title = pageType == 1 ? "设备添加" : "设备编辑";
    wx.setNavigationBarTitle({
      title,
    })
    this.setData({
      pageType
    })
    Promise.all([
      this.fetchResult("Common/Common/getEquipmentType"),
      this.fetchResult("Partner/Franchiser/franchiserList"),
      this.fetchResult("Partner/Franchiser/FranchiserVillageList", {
        row: 9999,
        page: 1
      }),
    ]).then(([equipmentTypes, franchiseers, villages]) => {
      this.setData({
        equipmentTypes,
        franchiseers,
        villages: villages.data
      })
      if (pageType == 2) {
        this.equipment_id = options.equipment_id;
        this.getEquipment();
      }
    })
  },



  scanCode(e) {
    const name = e.currentTarget.dataset.name;
    app.scanDeviceCode().then(res => {
      this.setData({
        [name]: res
      })
    }).catch(e => {
      app.showToast("扫码失败")
    })
  },







  getEquipment() {
    app.ajax({
      url: 'Partner/Equipment/getEquipment',
      data: {
        equipment_id: this.equipment_id
      },
      success: res => {
        if (res.data.code > 0) {
          const source = res.data.data;
          let equipmentTypeIndex = this.data.equipmentTypes.findIndex(item => item.id == source.equipment_type)
          let villageIndex = this.data.villages.findIndex(item => item.id == source.village_id);
          let franchiseerIndex = this.data.franchiseers.findIndex(item => item.id == source.partner_id)
          this.setData({
            equipment_name: source.equipment_name,
            equipment_number: source.equipment_number,
            address: source.address,
            villageIndex: ~villageIndex ? villageIndex : "",
            equipmentTypeIndex: ~equipmentTypeIndex ? equipmentTypeIndex : "",
            url_arrs: source.equipment_img,
            all_url_arrs: source.equipment_img_whole,
            franchiseerIndex: ~franchiseerIndex ? franchiseerIndex : '',
            longitude: source.longitude,
            latitude: source.latitude
          })
        } else {
          app.showToast(res.data.message);
        }
      },
      error: e => {
        app.showToast(res.data.message);
      }
    })
  },


  chooseImg() {
    let pictrues = this.data.all_url_arrs;
    let count = MAX_COUNT_IMAGE - pictrues.length;
    wx.chooseImage({
      count,
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '资源上传中',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          this.uploadFile(tempFilePaths[i], i, tempFilePaths.length - 1);
        }
      }
    })
  },

  uploadFile: function (tempFilePath, i, len) {
    var that = this;
    wx.uploadFile({
      url: app.globalData._url + 'Common/Common/upload',
      filePath: tempFilePath,
      name: 'file',
      success(res) {
        var source = JSON.parse(res.data.replace(/\ufeff/g, "") || "{}");
        if (source.code == 1000) {
          let all_url_arrs = that.data.all_url_arrs;
          let url_arrs = that.data.url_arrs;
          url_arrs.unshift(source.data.url);
          all_url_arrs.unshift(source.data.all_url);
          console.log(all_url_arrs, url_arrs);
          if (i == len) {
            wx.hideLoading();
          }
          that.setData({
            all_url_arrs,
            url_arrs
          })
        } else {
          app.showToast(`第${i+1}张图片上传失败`);
        }
      }
    })
  },

  deleteImg(e) {
    const index = e.currentTarget.dataset.index;
    let all_url_arrs = this.data.all_url_arrs;
    let url_arrs = this.data.url_arrs;
    all_url_arrs.splice(index, 1)
    url_arrs.splice(index, 1)
    this.setData({
      all_url_arrs,
      url_arrs
    })
  },

  navMapSetting() {
    if (this.data.villageIndex === "") {
      app.showToast("请先选择园区", "none", 2000, function () {});
      return;
    }
    wx.getSetting({
      success: settingRes => {
        if (settingRes.errMsg === "getSetting:ok") {
          const setting = settingRes.authSetting;
          if (setting["scope.userLocation"] == undefined || setting["scope.userLocation"]) {
            if (!this.data.latitude || !this.data.longitude) {
              wx.getLocation({
                type:"gcj02",
                success: results => {
                  this.setData({
                    latitude: results.latitude,
                    longitude: results.longitude
                  })
                  this.openLocation();
                },
                fail: res => {
                  app.showToast("请检查是否打开手机定位功能");
                }
              })
            } else {
              this.openLocation();
            }
          } else if (setting["scope.userLocation"] == false) {
            this.setData({
              authLocationTips: true
            })
          }
        }
      },
      fail: e => {
        app.showToast("getSetting fail");
      }
    })
  },



  openLocation() {
    wx.chooseLocation({
      latitude: this.data.latitude - 0,
      longitude: this.data.longitude - 0,
      success: res => {
        if (res.errMsg === "chooseLocation:ok") {
          this.setData({
            address: res.name,
            longitude: res.longitude,
            latitude: res.latitude
          })
        }
        console.log(res, "results")
      },
      fail: e => {
        if (e.errMsg === "chooseLocation:fail auth deny") {
          this.setData({
            authLocationTips: true
          })
        }
      }
    })
  },

  handleOpenSetting() {
    wx.openSetting({
      success: res => {
        if (res.errMsg === "openSetting:ok") {
          if (res.authSetting["scope.userLocation"]) {
            this.setData({
              authLocationTips: false
            })
            this.openLocation()
          }
        }
      },
      fail: e => {
        app.showToast("打开设置失败");
      }
    })
  },


  closeLocationTips() {
    this.setData({
      authLocationTips: false
    })
  },


  handlePicker(e) {
    const name = e.currentTarget.dataset.name;
    this.setData({
      [name]: e.detail.value
    })
  },


  pickVillage(e) {
    const name = e.currentTarget.dataset.name;
    const villages = this.data.villages;
    const value = e.detail.value;
    this.setData({
      [name]: value,
      address: villages[value].address,
      longitude: villages[value].lng,
      latitude: villages[value].lat,
    })
  },


  fetchResult(url, data = {}) {
    return new Promise((resolve, reject) => {
      app.ajax({
        url,
        data,
        success: res => {
          if (res.data.code > 0) {
            resolve(res.data.data);
          } else {
            app.showToast(res.data.message);
          }
        },
        error: e => {
          app.showToast("网络错误");
        }
      })
    })
  },

  //提交数据
  formSubmit(e) {
    const formData = e.detail.value;
    const equipmentTypeIndex = this.data.equipmentTypeIndex;
    const villageIndex = this.data.villageIndex;
    console.log(formData);
    if (formData.equipment_name === "") {
      app.showToast("请输入设备名称");
      return false;
    }
    if (this.data.franchiseerIndex === '') {
      app.showToast("请选择加盟商");
      return false;
    }
    if (equipmentTypeIndex === "") {
      app.showToast("请选择设备类型");
      return false;
    }
    if (formData.equipment_number === "") {
      app.showToast("缺少设备编号");
      return false;
    }
    if (this.data.villageIndex === "") {
      app.showToast("请选择园区");
      return false;
    }
    if (formData.address === "") {
      app.showToast("缺少安装地址");
      return false;
    }

    let url = "Partner/Equipment/addEquipment";
    if (this.data.pageType == 2) {
      formData.equipment_id = this.equipment_id;
      url = "Partner/Equipment/saveEquipment";
    }
    const village = this.data.villages[villageIndex];
    let latitude = this.data.latitude;
    let longitude = this.data.longitude;
    if ((!latitude || !longitude) && this.data.pageType == 1) {
      app.showToast("请点击定位图标重新定位");
      return false;
    }

    Object.assign(formData, {
      province: village.province,
      city: village.city,
      area: village.area,
      address: this.data.address,
      longitude,
      latitude,
      village_id: village.id,
      province_name: village.province_name,
      city_name: village.city_name,
      area_name: village.area_name,
      conf: village.set_template_id,
      equipment_type: this.data.equipmentTypes[equipmentTypeIndex].id,
      equipment_img: this.data.url_arrs,
      isfranchiser: 1,
      type: 1,
      partner_id: this.data.franchiseers[this.data.franchiseerIndex].id
    })
    app.ajax({
      url,
      data: formData,
      success: res => {
        wx.hideLoading();
        if (res.data.code > 0) {
          app.showToast(res.data.message, "success")
          setTimeout(() => {
            let pages = getCurrentPages();
            let targetPage = pages[pages.length - 2];
            targetPage.reloadData();
            wx.navigateBack()
          }, 1500)
        } else {
          app.showToast(res.data.message)
        }
      },
      error: e => {
        wx.hideLoading();
        app.showToast("网路错误");
      }
    })

  }

})
